package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"kuangstudy-mall/srvs/userrelation-srv/global"
	"kuangstudy-mall/srvs/userrelation-srv/model"
	"kuangstudy-mall/srvs/userrelation-srv/proto"
)

// 查询用户收藏列表
func (handler *UserRelationHandler) FindFavDetail(ctx context.Context, req *proto.UserFavRequest) (*proto.UserFavListResponse, error) {
	var userFavList []model.UserFav
	var response proto.UserFavListResponse

	var total int64
	global.DB.Where(&model.UserFav{UserId: req.UserId}).Count(&total)
	response.Total = int32(total)

	if result := global.DB.Scopes(Paginate(int(req.PageNo), int(req.PageSize))).Where(&model.UserFav{UserId: req.UserId}).Find(&userFavList); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "暂无收藏数据")
	}
	for _, userFav := range userFavList {
		response.Data = append(response.Data, &proto.UserFavResponse{
			UserId:  userFav.UserId,
			GoodsId: userFav.GoodsId,
		})
	}
	return &response, nil
}

// 保存收藏
func (handler *UserRelationHandler) SaveUserFav(ctx context.Context, req *proto.UserSaveFavRequest) (*proto.UserSaveFavResponse, error) {
	var userFav model.UserFav
	global.DB.Unscoped().Where(&model.UserFav{UserId: req.UserId, GoodsId: req.GoodsId}).First(&userFav)
	//if total > 0 {
	//	return nil, status.Errorf(codes.AlreadyExists, "你已收藏该商品")
	//}
	userFav.UserId = req.UserId
	userFav.GoodsId = req.GoodsId
	userFav.IsDeleted = 0
	global.DB.Save(&userFav)
	return &proto.UserSaveFavResponse{Flag: true}, nil
}

// 取消收藏
func (handler *UserRelationHandler) CancleUserFav(ctx context.Context, req *proto.UserSaveFavRequest) (*proto.UserSaveFavResponse, error) {
	if result := global.DB.Where(&model.UserFav{UserId: req.UserId, GoodsId: req.GoodsId}).Delete(&model.UserFav{}); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "收藏记录不存在")
	}
	return &proto.UserSaveFavResponse{Flag: true}, nil
}

// 判断用户是否收藏商品
func (handler *UserRelationHandler) GetUserFavDetail(ctx context.Context, req *proto.UserSaveFavRequest) (*proto.UserSaveFavResponse, error) {
	var total int64
	global.DB.Model(&model.UserFav{}).Where(&model.UserFav{UserId: req.UserId, GoodsId: req.GoodsId}).Count(&total)
	return &proto.UserSaveFavResponse{Flag: total > 0}, nil
}
